package com.example.bookstore.service.impl;

import com.example.bookstore.entity.Order;
import com.example.bookstore.entity.OrderItem;
import com.example.bookstore.entity.Product;
import com.example.bookstore.enums.ResultEnum;
import com.example.bookstore.form.orderform.InsertOrderForm;
import com.example.bookstore.mapper.OrderItemMapper;
import com.example.bookstore.mapper.OrderMapper;
import com.example.bookstore.mapper.ProductMapper;
import com.example.bookstore.service.OrderService;
import com.example.bookstore.utils.PageUtil;
import com.example.bookstore.utils.ResultVOUtil;
import com.example.bookstore.utils.TimeUtil;
import com.example.bookstore.vo.ResultVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.util.*;

@Repository
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    ProductMapper productMapper;

    @Override
    public ResultVO InsertOrder(InsertOrderForm insertOrderForm) throws ParseException {
        Order order = new Order();

        order.setMoney(insertOrderForm.getMoney());
        order.setreceiverAddress(insertOrderForm.getReceiverAddress());
        order.setreceiverName(insertOrderForm.getReceiverName());
        order.setreceiverPhone(insertOrderForm.getReceiverPhone());
        order.setuserId(insertOrderForm.getUserId());

        order.setpayState(0);
        order.setorderTime(TimeUtil.getNowDateTime());

        try {
            orderMapper.InsertOrder(order);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        //添加对应的订单数量详情
        OrderItem orderItem = new OrderItem();
        orderItem.setproductId(insertOrderForm.getProductId());
        orderItem.setbuyNum(insertOrderForm.getBuyNum());
        orderItem.setorderId(order.getorderId());

        orderItemMapper.InsertOrderItem(orderItem);

        //获取当前订单数量详情
        orderItem = orderItemMapper.SelectItemById(order.getorderId());
        //查询当前还有多少库存
        Product product = productMapper.SelectBookById(insertOrderForm.getProductId());
        if(product.getproductPnum() < insertOrderForm.getBuyNum()){
            orderItemMapper.DeleteOrderItem(orderItem.getorderId());
            orderMapper.DeleteOrder(order.getorderId());
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        } else {
            Integer pnum = product.getproductPnum() - insertOrderForm.getBuyNum();
            productMapper.UpdateBookPnum(pnum,product.getproductId());
        }

        return ResultVOUtil.success(order);
    }

    @Override
    public ResultVO DeleteOrder(Integer orderId) {
        try {
            orderMapper.DeleteOrder(orderId);
            orderItemMapper.DeleteOrderItem(orderId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO UpdatePayState(Integer orderId) {
        try{
            orderMapper.UpdatePayState(orderId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success();
    }

    @Override
    public ResultVO SelectOrderById(Integer orderId) {
        Order order = new Order();
        try{
            order = orderMapper.SelectOrderById(orderId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }
        return ResultVOUtil.success(order);
    }

    @Override
    public ResultVO SelectOrderByUser(Integer userId) {
        List<Order> orderList = new ArrayList<>();
        try{
            orderList = orderMapper.SelectOrderByUser(userId);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap = PageUtil.getMap(orderList);

        return ResultVOUtil.success(hashMap);
    }

    @Override
    public ResultVO ShowAllOrderByWeek() {
        List<Order> orderList = new ArrayList<>();
        try {
            orderList = orderMapper.ShowAllOrderByWeek();
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.NORMAL_ERROR);
        }

        //用hashMap记录产品(图书)id，以及对应的购买数量
        HashMap<Integer,Integer> totalMap = new HashMap<>();

        Integer[] key = new Integer[totalMap.size()];
        Integer[] value = new Integer[totalMap.size()];

        for (Order tOrder:orderList) {
            OrderItem orderItem = orderItemMapper.SelectItemById(tOrder.getorderId());
            if(totalMap.containsKey(orderItem.getproductId())){
                Integer buyNum = totalMap.get(orderItem.getproductId());
                buyNum = buyNum + orderItem.getbuyNum();
                totalMap.put(orderItem.getproductId(),buyNum);

            }else {
                totalMap.put(orderItem.getproductId(),orderItem.getbuyNum());
            }
        }

        List<Map.Entry<Integer,Integer>> entryList = new ArrayList<Map.Entry<Integer, Integer>>(totalMap.entrySet());

        Collections.sort(entryList, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        //该链表用于记录经过排序后的产品，此时产品排序后是从高到低
        List<Product> productList = new ArrayList<>();

        for (Map.Entry<Integer,Integer> mapping: entryList) {
            System.out.println(mapping.getKey()+":  "+mapping.getValue());

            Product product = productMapper.SelectBookById(mapping.getKey());
            productList.add(product);
        }

        return ResultVOUtil.success(productList);
    }

}
